<template>
  <div class="app-container">
    <el-tabs type="border-card" v-model="activeName" @tab-click="tabClick">
      <el-tab-pane :label="$t('基础信息')" name="basic">
        <basic-info ref="basic"></basic-info>
      </el-tab-pane>
      <el-tab-pane :label="$t('收费信息')" name="charge">
        <charging-info ref="charge"></charging-info>
      </el-tab-pane>
      <!-- <el-tab-pane :label="$t('注册协议')" name="register">
        <div class="editor_box">
          <editor id="register" v-model="registerHtml" :init="registerInit"></editor>
          <el-button
            class="btn"
            type="primary"
            @click="agreement('registration_agreement')"
            v-if="permissions.indexOf('/set/save') != -1"
          >{{$t('提交')}}</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('充值协议')" name="topup">
        <div class="editor_box">
          <editor id="topup" v-model="topupHtml" :init="topupInit"></editor>
          <el-button
            class="btn"
            type="primary"
            @click="agreement('recharge_agreement')"
            v-if="permissions.indexOf('/set/save') != -1"
          >{{$t('提交')}}</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('用户协议')" name="user">
        <div class="editor_box">
          <editor id="user" v-model="userHtml" :init="userInit"></editor>
          <el-button
            class="btn"
            type="primary"
            @click="agreement('user_agreement')"
            v-if="permissions.indexOf('/set/save') != -1"
          >{{$t('提交')}}</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('隐私声明')" name="privacy">
        <div class="editor_box">
          <editor id="privacy" v-model="privacyHtml" :init="privacyInit"></editor>
          <el-button
            class="btn"
            type="primary"
            @click="agreement('privacy_agreement')"
            v-if="permissions.indexOf('/set/save') != -1"
          >{{$t('提交')}}</el-button>
        </div>
      </el-tab-pane> -->
      <el-tab-pane :label="$t('小程序地图图标')" name="icon">
        <div class="basic">
          <div class="img_list">
            <div class="upload_img" v-if="location_icon">
              <img :src="location_icon" />
            </div>
            <el-upload :action="protocol + '//cdb.workair.vip/operate/set/fileUpload'" :headers="{ token, ocode }"
              name="img_file" :data="{ type: 'image' }" :file-list="locationFile" :limit="1" :on-exceed="handleExceed"
              :on-success="handleSuccess" :on-remove="handleRemove" :on-error="handleError" list-type="picture">
              <el-button type="primary">{{ $t('选择文件') }}</el-button>
            </el-upload>
          </div>
          <el-button class="submit_btn" type="primary" @click="loca_submit"
            v-if="permissions.indexOf('/set/save') != -1">{{ $t('提交') }}</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('小程序租借后广告')" name="adver">
        <div class="basic">
          <div class="ipt_list u-f u-f-ac">
            <span class="lable font14 text_black">{{ $t('停留时间') }}（3-60 {{ $t('秒') }} ）：</span>
            <el-input v-model="adver_second" maxlength="2" :placeholder="$t('请输入')"></el-input>
          </div>
          <div class="ipt_list u-f u-f-ac">
            <span class="lable font14 text_black">{{ $t('小程序跳转地址') }}：</span>
            <el-input v-model="adver_url" :placeholder="$t('请输入')"></el-input>
          </div>
          <div class="txt_list u-f u-f-ac">
            <p class="lable u-f u-f-ac">
              <span class="font14 text_danger" style="margin-right: 3px;">*</span>
              <span class="font14 text_black">是否开启：</span>
            </p>
            <el-radio v-model="concealed" :label="'0'">关闭</el-radio>
            <el-radio v-model="concealed" :label="'1'">开启</el-radio>
          </div>
          <div class="img_list">
            <div class="upload_img" v-if="adver_img">
              <img :src="adver_img" />
            </div>
            <el-upload :action="protocol + '//cdb.workair.vip/operate/set/fileUpload'" :headers="{ token, ocode }"
              name="img_file" :data="{ type: 'image' }" :file-list="adverFile" :limit="1" :on-exceed="handleAdvExceed"
              :on-success="handleAdvSuccess" :on-remove="handleAdvRemove" :on-error="handleAdvError" list-type="picture">
              <el-button type="primary">{{ $t('选择文件') }}</el-button>
            </el-upload>
          </div>
          <el-button class="submit_btn" type="primary" @click="adv_submit"
            v-if="permissions.indexOf('/set/save') != -1">{{ $t('提交') }}</el-button>
        </div>
      </el-tab-pane>

      <!-- <el-tab-pane :label="$t('小程序banner图')" name="dct">
        <el-upload action="#" list-type="picture-card" :multiple="true" :limit="5" :auto-upload="false"
          :on-exceed="onExceed" :file-list="fileList" :before-upload="onBeforeUpload" :on-change="_onchange">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in"></i>
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                <i class="el-icon-download"></i>
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemoves(file)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>


      </el-tab-pane> -->
    </el-tabs>
    <refresh @click="handleRefresh"></refresh>

  </div>
</template>

<script>
import basicInfo from "components/setting/basic-info.vue";
import chargingInfo from "components/setting/charging-info.vue";
import util from "@/assets/js/util.js";
import { mapState } from "vuex";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver";
import "tinymce/plugins/image"; // 插入上传图片插件
export default {
  name: "set-index",
  data() {
    let that = this;
    return {

      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: [],

      activeName: 'basic',
      isRefresh: false,
      protocol: window.location.protocol,
      registerHtml: "",
      registerInit: {
        language_url: "/tinymce/langs/zh_CN.js", // 语言包的路径
        language: "zh_CN", //语言
        skin_url: "/tinymce/skins/ui/oxide", // skin路径
        height: 500, //编辑器高度
        menubar: false, // 隐藏最上方menu菜单
        paste_data_images: true, // 允许粘贴图像
        // 注册功能组件
        plugins: "image",
        // 注册工具栏
        toolbar: [
          "newdocument undo redo | formatselect visualaid|cut copy paste selectall image| bold italic underline strikethrough |codeformat blockformats| superscript subscript  | forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent |  removeformat "
        ],
        images_upload_handler(blobInfo, success, failure) {
          that.tinyRegisInit(blobInfo, success, failure);
        }
      },
      topupHtml: "",
      topupInit: {
        language_url: "/tinymce/langs/zh_CN.js", // 语言包的路径
        language: "zh_CN", //语言
        skin_url: "/tinymce/skins/ui/oxide", // skin路径
        height: 500, //编辑器高度
        menubar: false, // 隐藏最上方menu菜单
        paste_data_images: true, // 允许粘贴图像
        // 注册功能组件
        plugins: "image",
        // 注册工具栏
        toolbar: [
          "newdocument undo redo | formatselect visualaid|cut copy paste selectall image| bold italic underline strikethrough |codeformat blockformats| superscript subscript  | forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent |  removeformat "
        ],
        images_upload_handler(blobInfo, success, failure) {
          that.tinyTopupInit(blobInfo, success, failure);
        }
      },
      userHtml: "",
      userInit: {
        language_url: "/tinymce/langs/zh_CN.js", // 语言包的路径
        language: "zh_CN", //语言
        skin_url: "/tinymce/skins/ui/oxide", // skin路径
        height: 500, //编辑器高度
        menubar: false, // 隐藏最上方menu菜单
        paste_data_images: true, // 允许粘贴图像
        // 注册功能组件
        plugins: "image",
        // 注册工具栏
        toolbar: [
          "newdocument undo redo | formatselect visualaid|cut copy paste selectall image| bold italic underline strikethrough |codeformat blockformats| superscript subscript  | forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent |  removeformat "
        ],
        images_upload_handler(blobInfo, success, failure) {
          that.tinyUserInit(blobInfo, success, failure);
        }
      },
      privacyHtml: "",
      privacyInit: {
        language_url: "/tinymce/langs/zh_CN.js", // 语言包的路径
        language: "zh_CN", //语言
        skin_url: "/tinymce/skins/ui/oxide", // skin路径
        height: 500, //编辑器高度
        menubar: false, // 隐藏最上方menu菜单
        paste_data_images: true, // 允许粘贴图像
        // 注册功能组件
        plugins: "image",
        // 注册工具栏
        toolbar: [
          "newdocument undo redo | formatselect visualaid|cut copy paste selectall image| bold italic underline strikethrough |codeformat blockformats| superscript subscript  | forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent |  removeformat "
        ],
        images_upload_handler(blobInfo, success, failure) {
          that.tinyPrivacyInit(blobInfo, success, failure);
        }
      },
      location_icon: "",
      location_id: "",
      locationFile: [],
      adver_img: "",
      adver_id: "",
      concealed: 0,
      adverFile: [],
      adver_second: "",
      adver_url: "",
    };
  },
  computed: {
    ...mapState(["token", "ocode", "permissions"])
  },
  components: {
    basicInfo,
    chargingInfo,
    Editor
  },
  mounted() {
    tinymce.init({
      selector: "#register"
    });
    tinymce.init({
      selector: "#topup"
    });
    tinymce.init({
      selector: "#user"
    });
    tinymce.init({
      selector: "#privacy"
    });
  },
  methods: {
    // 图片上传成功的函数
    i_handleSuccess(response, file, fileList) {
      this.returnBack(fileList);
    },
    handleRemoves(file) {
      let uid = file.uid
      let index = this.fileList.findIndex((e) => uid == e.uid)
      this.fileList.splice(index, 1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    onExceed() {
      this.$message.warning("最多上传5张图片！");
    },
    _onchange(file, fileList) {
      this.fileList = fileList
    },
    onBeforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 1MB!');
        return false
      }
      // 获取文件的后缀名
      const extension = file.name.split('.').pop().toLowerCase();

      // 验证文件类型
      const allowedExtensions = ['jpg', 'png'];
      const isValidType = allowedExtensions.includes(extension);
      if (!isValidType) {
        this.$message.error('只能上传jpg和png文件！');
      }

      // 返回 false 可以阻止文件上传
      return isValidType;
    },



    handleRefresh() {
      this.activeName = 'basic'
      this.$refs.basic.getData()
      this.$refs.charge.getData()
    },
    tabClick(val) {
      switch (Number(val.index)) {
        // case 2:
        //   this.getData("registration_agreement");
        //   break;
        // case 3:
        //   this.getData("recharge_agreement");
        //   break;
        // case 4:
        //   this.getData("user_agreement");
        //   break;
        // case 5:
        //   this.getData("privacy_agreement");
        //   break;
        case 2:
          this.getData("location_icon");
          break;
        case 3:
          this.getData("order_adv");
          break;
        default:
          break;
      }
    },
    getData(type) {
      util
        .$http2("/set/info", {
          type
        })
        .then(res => {
          if (res.code == 1) {
            switch (type) {
              case "registration_agreement":
                this.registerHtml = res.data;
                break;
              case "recharge_agreement":
                this.topupHtml = res.data;
                break;
              case "user_agreement":
                this.userHtml = res.data;
                break;
              case "privacy_agreement":
                this.privacyHtml = res.data;
                break;
              case "location_icon":
                this.location_icon = res.data.file;
                if (res.data.file && res.data.file != "0") {
                  this.locationFile = [
                    {
                      name: 1,
                      url: res.data.file
                    }
                  ];
                }
                break;
              case "order_adv":
                this.adver_img = res.data.file;
                this.adver_second = res.data.second;
                this.adver_url = res.data.url;
                this.concealed = res.data.concealed;
                if (res.data.file && res.data.file != "0") {
                  this.adverFile = [
                    {
                      name: 1,
                      url: res.data.file
                    }
                  ];
                }
                break;
              default:
                break;
            }
          }
        });
    },
    agreement(sta) {
      let data = {};
      switch (sta) {
        case "registration_agreement":
          data = {
            type: "agreement",
            field: "registration_agreement",
            registration_agreement: this.registerHtml
          };
          break;
        case "recharge_agreement":
          data = {
            type: "agreement",
            field: "recharge_agreement",
            recharge_agreement: this.topupHtml
          };
          break;
        case "user_agreement":
          data = {
            type: "agreement",
            field: "user_agreement",
            user_agreement: this.userHtml
          };
          break;
        case "privacy_agreement":
          data = {
            type: "agreement",
            field: "privacy_agreement",
            privacy_agreement: this.privacyHtml
          };
          break;
        default:
          break;
      }
      util.$http("/set/save", data).then(res => {
        if (res.code == 1) {
          this.$message({
            message: res.msg,
            type: "success"
          });
        }
      });
    },
    tinyRegisInit(blobInfo, success, failure) {
      console.log("tinyRegisInit")
      let formData = new FormData();
      formData.append("img_file", blobInfo.blob());
      formData.append("type", "image");
      util
        .$http("/screenadv/fileUpload", formData)
        .then(res => {
          success(res.path);
        })
        .catch(err => {
          failure(this.$t("上传失败"));
        });
    },
    tinyTopupInit(blobInfo, success, failure) {
      console.log("tinyTopupInit")
      let formData = new FormData();
      formData.append("img_file", blobInfo.blob());
      formData.append("type", "image");
      util
        .$http("/screenadv/fileUpload", formData)
        .then(res => {
          success(res.path);
        })
        .catch(err => {
          failure(this.$t("上传失败"));
        });
    },
    tinyUserInit(blobInfo, success, failure) {
      console.log("tinyUserInit")
      let formData = new FormData();
      formData.append("img_file", blobInfo.blob());
      formData.append("type", "image");
      util
        .$http("/screenadv/fileUpload", formData)
        .then(res => {
          success(res.path);
        })
        .catch(err => {
          failure(this.$t("上传失败"));
        });
    },
    tinyPrivacyInit(blobInfo, success, failure) {
      console.log("tinyPrivacyInit")
      let formData = new FormData();
      formData.append("img_file", blobInfo.blob());
      formData.append("type", "image");
      util
        .$http("/screenadv/fileUpload", formData)
        .then(res => {
          success(res.path);
        })
        .catch(err => {
          failure(this.$t("上传失败"));
        });
    },
    handleSuccess(response, file) {
      this.location_id = response.msg;
      this.location_icon = response.path;
    },
    handleRemove() {
      this.location_id = "";
      this.location_icon = "";
    },
    handleError(err) {
      this.$message({
        message: this.$t("上传失败"),
        type: "warning"
      });
    },
    handleExceed() {
      this.$message({
        message: this.$t("只能上传一张"),
        type: "warning"
      });
    },
    loca_submit() {
      util
        .$http("/set/save", {
          type: "location_icon",
          image: this.location_id
        })
        .then(res => {
          if (res.code == 1) {
            this.$message({
              message: res.msg,
              type: "success"
            });
          }
        });
    },
    handleAdvSuccess(response, file) {
      this.adver_id = response.msg;
      this.adver_img = response.path;
    },
    handleAdvRemove() {
      this.adver_id = "";
      this.adver_img = "";
    },
    handleAdvError(err) {
      this.$message({
        message: this.$t("上传失败"),
        type: "warning"
      });
    },
    handleAdvExceed() {
      this.$message({
        message: this.$t("只能上传一张"),
        type: "warning"
      });
    },
    adv_submit() {
      // console.log('打印出来奥');
      // console.log(this.adver_id);
      // return;
      util
        .$http("/set/save", {
          type: "order_adv",
          image: this.adver_img,
          second: this.adver_second,
          url: this.adver_url,
          concealed: this.concealed
        })
        .then(res => {
          if (res.code == 1) {
            this.$message({
              message: res.msg,
              type: "success"
            });
          }
        });
    }
  }
};
</script>

<style scoped>
.editor_box {
  max-width: 1200px;
  padding: 20px 0 30px 20px;
}

.editor_box .btn {
  margin-top: 40px;
}

.basic {
  padding: 20px 0 20px 20px;
}

.basic .ipt_list {
  margin-bottom: 20px;
}

.basic .ipt_list .lable {
  display: inline-block;
  width: 150px;
}

.basic .ipt_list .el-input {
  width: 200px;
}

.basic .img_list {
  max-width: 400px;
  margin-bottom: 30px;
}

.basic .img_list .upload_img {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
}

.basic .img_list img {
  width: 100%;
  height: 100%;
}
</style>
